package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import DAO.RollDao;
import DAO.UserDao;
import database.DBManager;

/**
 * Servlet implementation class ConfigServlet
 */
public class ConfigServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	private DBManager myDb;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConfigServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	public void init(ServletConfig servletconfig) {
		// Initialisatie
		myDb = (DBManager) servletconfig.getServletContext().getAttribute("dbmanager");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		String[] url = request.getQueryString().split( "=" );
		if( url[0].equals("page") && url[1].equals("first")) {
			UserDao ud = new UserDao(myDb);
			ArrayList<User> users = ud.getUsers();
			RollDao rd = new RollDao(myDb);
			request.setAttribute("rolls", rd.getRolls());
			if(users.isEmpty()){
				view = request.getRequestDispatcher("WEB-INF/config.jsp");
			}else{
				view = request.getRequestDispatcher("WEB-INF/login.jsp");
			}
		}
		view.forward( request, response );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		String[] url = request.getQueryString().split( "=" );
		if( url[0].equals("page") && url[1].equals("config")) {
			request.setAttribute("config", "true");
			RollDao rd = new RollDao(myDb);
			request.setAttribute("rolls", rd.getRolls());
			view = request.getRequestDispatcher( "index.jsp" );
		}else if(url[0].equals("page") && url[1].equals("added")){
			addKlant(request);
			view = request.getRequestDispatcher("WEB-INF/login.jsp");
		}
		view.forward( request, response );
	}
	
	private boolean addKlant(HttpServletRequest request){
		boolean succeeded = false;
		if(request.getParameter("wachtwoord").equals(request.getParameter("wachtwoord2"))){
			UserDao udao = new UserDao(myDb);
			String gebruikersnaam = request.getParameter("gebruikersnaam");
			int roll = Integer.parseInt(request.getParameter("rolls"));
			udao.createKlant(gebruikersnaam, request.getParameter("wachtwoord"), roll);
			succeeded = true;
		}
		return succeeded;
	}

}
